package very.util.session

import java.util.UUID

import very.util.redis.RedisPool

import scala.collection.JavaConverters._
import scala.collection.mutable

trait RedisSession[Entity] {
  protected def redisPool: RedisPool
  protected def encode: Entity => Map[String, String]
  protected def decode: mutable.Map[String, String] => Entity

  def generateSession(userSession: Entity, expires: Int = 12 * 60 * 60): String = {
    val uuid = UUID.randomUUID().toString
    redisPool.run { redis =>
      redis.hmset(
        uuid,
        encode(userSession).asJava
      )
      redis.expire(uuid, expires)
    }
    uuid
  }

  def deleteSession(sessionId: String): Unit =
    redisPool.run(_.del(sessionId))

  def getSession(sessionId: String): Option[Entity] = {
    redisPool.run { redis =>
      val map = redis.hgetAll(sessionId).asScala
      if (map.isEmpty) {
        None
      } else {
        Some(decode(map))
      }
    }
  }
}
